package com.xgame.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.xgame.service.UserService;
import com.xgame.util.ObjectJsonUtil;
import com.xgame.util.VM;
import com.xgame.mybatis.model.User;

public class BaseLoginMethod
{
	protected final Logger log = LoggerFactory.getLogger(getClass());
	protected static String defaultKey = "lys";
	protected static final String SID = "SID"; //key是SID,value是用户名密码
	
	@Autowired
	UserService userService;
	
	protected User getLoginUser(HttpServletRequest request,HttpServletResponse response) {
		User user=(User)request.getSession().getAttribute("USER");
		if(user == null){
			user=(User) getCookieObject("USER", User.class,request);
		}
		return user;
	}
	
//	protected ClientMoblieUser getLoginClient(HttpServletRequest request,HttpServletResponse response) {
//		return null;
//	}
	
	protected String getClientIp(HttpServletRequest request)
	{
		String ip = request.getHeader("X-Real-IP");
			if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
			   ip = request.getHeader("x-forwarded-for");
			}
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getHeader("WL-Proxy-Client-IP"); 
	       } 
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
	           ip = request.getRemoteAddr(); 
	       } 
		return ip;
	}
	
	protected void insertActionLog(HttpServletRequest request, User user, Long appId, Long gameId, String action)
	{
//		log.info(account.getId()+"登录日志->"+accountActionLog.getAccountId()+"sid="+request.getSession().getId());
	}

	/**
	 * 操作完成后返回操作失败的JSON格式的数据
	 * @param response
	 */
	protected void generateFail(HttpServletRequest request, HttpServletResponse response)
	{
		response.setContentType("application/json; charset=UTF-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out;
		try
		{
			out = response.getWriter();
			String msg="{\"errCode\":301,\"success\":false,\"msg\":\"登录失败\"}";
			log.info("登陆返回301."+request.getRequestURI());
			log.info("SID->"+request.getSession().getId());
			out.print(msg);
			out.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 用户信息放入session中
	 * 
	 * @param user
	 */
	protected void setUserSession(User user,HttpServletRequest request) {
		request.getSession().setAttribute("USER", user);
	}
	
	/**
     * 获取指定的配置
     * @param name
     * @return
     */
    protected String getParam(HttpServletRequest request,String name){
        return getParam(request,name, "");
    }
    /**
     * 根据参数名称获取参数值，如果没有找到则以默认值返回
     * @param name
     * @param defaultValue
     * @return
     */
    protected String getParam(HttpServletRequest request,String name, String defaultValue){
        String strValue = request.getParameter(name);
        return strValue == null ? defaultValue : strValue;
    }
    
    protected void savaLoginCid(HttpServletRequest request,HttpServletResponse response, Long CID)
	{
		request.getSession().setAttribute("CID", CID);
		Cookie cookie = new Cookie("CID", String.valueOf(CID));
		cookie.setMaxAge(365 * 24 * 3600);// 365天
		cookie.setPath("/");
		response.addCookie(cookie);
	}
	
	/**
	 * @throws Y6Exception 
	 * 获得登录用户主键
	 * @param @return
	 * @return Long
	 * @throws
	 */
	protected Long getLoginUserId(HttpServletRequest request) 
	{
		Long userId = null;
		User user = (User) request.getSession().getAttribute("loginUser");
			if (user != null){
				userId=user.getUid();
			}
			if (userId == null)
			{
				log.info("用户编号无法获取,用户未登录.");
//				generateFail(getRequest(), getResponse()); //返回失败信息
			}
		return userId;
	}
	
	/********************* 获取访问参数 *******************/
	/******************* 操作Cookie ********************/
//	protected void savaLoginInfo(User user, HttpServletResponse response) {
//		String key = AutoLoginKeyUtil.getLKey(user.getName(),
//				user.getPassword());
//		this.getRequest().getSession().setAttribute("LKEY", key);
//		Cookie cookie = new Cookie("LKEY", key);
//		cookie.setMaxAge(30 * 24 * 3600);// 30天
//		cookie.setPath("/");
//		response.addCookie(cookie);
//	}

	protected void savaSid(String sid,HttpServletRequest request,HttpServletResponse response) {
		request.getSession().setAttribute("SID", sid);
		Cookie cookie = new Cookie("SID", sid);
		cookie.setMaxAge(30 * 24 * 3600);// 30天
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	/**
	 * 六小时注册数
	 * 
	 * @param ipValue
	 * @param response
	 */
	protected void savaIpNum(String ip, String ipValue
			,HttpServletRequest request,HttpServletResponse response) {
		request.getSession().setAttribute(ip, ipValue);
		Cookie cookie = new Cookie(ip, ipValue);
		cookie.setMaxAge(VM.getInatance().getHour() * 60);// 6小时
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	/**
	 * 获取指定键的Cookie
	 * 
	 * @param cookieName
	 * @return 如果找到Cookie则返回 否则返回null
	 */
	protected Cookie getCookie(String cookieName,HttpServletRequest request) {
		if (StringUtils.isEmpty(cookieName)
				|| request.getCookies() == null)
			return null;
		for (Cookie cookie : request.getCookies()) {
			System.out.println(cookie.getName());
			if (cookieName.equals(cookie.getName()))
				return cookie;
		}
		return null;
	}

	/**
	 * 获取指定键的Cookie值
	 * 
	 * @param cookieName
	 * @return 如果找到Cookie则返回 否则返回null
	 */
	protected String getCookieValue(String cookieName,HttpServletRequest request) {
		Cookie cookie = this.getCookie(cookieName,request);
		return cookie == null ? null : cookie.getValue();
	}

	/**
	 * 删除指定的Cookie
	 * 
	 * @param cookieName
	 */
	protected void removeCookie(String cookieName, HttpServletResponse response) {
		// HttpServletResponse response = this.getResponse();
		Cookie cookie = new Cookie(cookieName, null);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

	/**
	 * 保存一个对象到Cookie里 Cookie只在会话内有效
	 * 
	 * @param cookieName
	 * @param inst
	 */
	protected void setCookie(String cookieName, Object inst) {
		this.setCookie(cookieName, "/", inst);
	}

	/**
	 * 保存一个对象到Cookie Cookie只在会话内有效
	 * 
	 * @param cookieName
	 * @param path
	 * @param inst
	 */
	protected void setCookie(String cookieName, String path, Object inst) {
		if (StringUtils.isEmpty(cookieName) || inst == null)
			return;
		String strCookieString = this.object2CookieString(inst);
		this.setCookie(cookieName, path, strCookieString);
	}

	/**
	 * 保存一个对象到Cookie
	 * 
	 * @param cookieName
	 * @param inst
	 * @param expiry
	 *            (秒)设置Cookie的有效时长， 负数不保存，0删除该Cookie
	 */
	protected void setCookie(String cookieName, Object inst, int expiry) {
		this.setCookie(cookieName, "/", inst, expiry);
	}

	/**
	 * 保存一个对象到Cookie
	 * 
	 * @param cookieName
	 * @param path
	 * @param inst
	 * @param expiry
	 *            (秒)设置Cookie的有效时长， 负数不保存，0删除该Cookie
	 * @deprecated
	 */
	protected void setCookie(String cookieName, String path, Object inst,
			int expiry) {
		if (StringUtils.isEmpty(cookieName) || inst == null || expiry < 0)
			return;
		String strCookieString = this.object2CookieString(inst);
		this.setCookie(cookieName, path, strCookieString, expiry);
	}

	/**
	 * 保存一个对象到Cookie里 Cookie只在会话内有效
	 * 
	 * @param cookieName
	 * @param cookieValue
	 * @deprecated
	 */
	protected void setCookie(String cookieName, String cookieValue) {
		this.setCookie(cookieName, "/", cookieValue);
	}

	/**
	 * 保存一个对象到Cookie Cookie只在会话内有效
	 * 
	 * @param cookieName
	 * @param path
	 * @param cookieValue
	 */
	protected void setCookie(String cookieName, String path,
			String cookieValue, HttpServletResponse response) {
		// HttpServletResponse response = this.getResponse();
		if (StringUtils.isEmpty(cookieName) || cookieValue == null)
			return;
		Cookie cookie = new Cookie(cookieName, cookieValue);
		if (!StringUtils.isEmpty(path)) {
			cookie.setPath(path);
		}
		response.addCookie(cookie);
	}

	/**
	 * 保存一个对象到Cookie
	 * 
	 * @param cookieName
	 * @param cookieValue
	 * @param expiry
	 *            (秒)设置Cookie的有效时长， 负数不保存，0删除该Cookie
	 */
	protected void setCookie(String cookieName, String cookieValue, int expiry) {
		this.setCookie(cookieName, "/", cookieValue, expiry);
	}

	/**
	 * 保存一个对象到Cookie
	 * 
	 * @param cookieName
	 * @param path
	 * @param cookieValue
	 * @param expiry
	 *            (秒)设置Cookie的有效时长， 负数不保存，0删除该Cookie
	 * @deprecated
	 */
	protected void setCookie(String cookieName, String path,
			String cookieValue, int expiry, HttpServletResponse response) {

		if (StringUtils.isEmpty(cookieName) || cookieValue == null
				|| expiry < 0)
			return;
		// HttpServletResponse response = this.getResponse();
		if (StringUtils.isEmpty(cookieName) || cookieValue == null)
			return;
		Cookie cookie = new Cookie(cookieName, cookieValue);
		if (!StringUtils.isEmpty(path)) {
			cookie.setPath(path);
		}
		cookie.setMaxAge(expiry);
		response.addCookie(cookie);
	}

	/**
	 * 把对象转换为Cookie存贮字串
	 * 
	 * @param inst
	 * @return
	 */
	private String object2CookieString(Object obj) {
		if (obj == null)
			return "";
		return ObjectJsonUtil.object2JsonString(obj);
	}

	/**
	 * 从Cookie中获对对象
	 * 
	 * @param cookieName
	 * @param inst
	 * @return 如果获取转换成功，则返回true, 否则返回false
	 */
	protected Object getCookieObject(String cookieName, Class<?> clazz,HttpServletRequest request) {
		String jsonStr = getCookieValue(cookieName,request);
		return ObjectJsonUtil.JsonStringToObj(jsonStr, clazz);
	}

}
